package com.battle.service.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.battle.pojo.entity.Label;
import com.battle.pojo.entity.LabelMp;
import com.battle.pojo.entity.User;
import com.battle.pojo.param.label.*;
import com.battle.pojo.vo.label.*;
import com.battle.pojo.dto.label.*;
import com.battle.service.repository.in.LabelMpRepository;
import com.battle.service.repository.in.LabelRepository;
import com.battle.service.repository.in.UserRepository;
import com.battle.service.service.in.LabelService;
import nirvana.core.domains.vo.PageResult;
import nirvana.core.exceptions.BizException;
import nirvana.core.utils.ids.IdGenerator;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 【描 述】：标签服务
 * 【环 境】：J2SE 17
 * 【详 细】：
 */
@Service
public class LabelServiceImpl implements LabelService {

    private final LabelRepository labelRepository;
    private final LabelMpRepository mpRepository;
    private final UserRepository userRepository;

    public LabelServiceImpl(LabelRepository labelRepository, LabelMpRepository mpRepository, UserRepository userRepository) {
        this.labelRepository = labelRepository;
        this.mpRepository = mpRepository;
        this.userRepository = userRepository;
    }


    /**
     * 创建标签
     *
     * @param param
     */
    @Override
    public void createLabel(CreateLabelParam param) {
        param.setType(0);
        Long count = labelRepository.count(
                new LambdaQueryWrapper<Label>()
                        .eq(Label::getName, param.getName())
                        .eq(Label::getType, param.getType())
                        .eq(Label::getIsDelete, false)
        );
        if (count > 0) {
            throw new BizException("标签名称已存在");
        }


        Label label = new Label();
        BeanUtils.copyProperties(param, label);
        Long id = IdGenerator.SNOW.generate();
        label.setId(id);
        labelRepository.create(label);
    }

    /**
     * 修改标签
     *
     * @param param
     */
    @Override
    public void editLabel(EditLabelParam param) {
        Long id = param.getId();
        Label label = labelRepository.getByIdCheck(id);
        BeanUtils.copyProperties(param, label);
        labelRepository.edit(label);
    }

    /**
     * 移除标签
     *
     * @param id
     */
    @Override
    public void removeLabel(Long id) {
        //检查是否已经绑定
        List<LabelMp> labelMps = mpRepository.getBaseMapper().selectList(new LambdaQueryWrapper<LabelMp>()
                .eq(LabelMp::getLabelId, id)
                .eq(LabelMp::getIsDelete, 0)
        );
        if (CollectionUtil.isNotEmpty(labelMps)) {
            throw new BizException("该标签下有绑定，不能删除");
        }
        labelRepository.removeById(id);
    }

    /**
     * 启动/禁用标签
     *
     * @param id
     */
    @Override
    public void enabledLabel(Long id) {
        Label label = labelRepository.getByIdCheck(id);
        label.setIsDisable(!label.getIsDisable());
        labelRepository.edit(label);
    }

    /**
     * 获取标签详情
     *
     * @param id
     * @return
     */
    @Override
    public GetLabelVo getLabel(Long id) {
        Label label = labelRepository.getByIdCheck(id);
        GetLabelVo vo = new GetLabelVo();
        BeanUtils.copyProperties(label, vo);
        return vo;
    }

    /**
     * 获取标签 列表
     *
     * @param param
     * @return
     */
    @Override
    public PageResult<GetLabelListVo> getLabelList(GetLabelListParam param) {

        SelectLabelDto dto = new SelectLabelDto();
        BeanUtils.copyProperties(param, dto);
        //默认为战力标签
        dto.setType(0);
        Page<Label> page = labelRepository.selectLabel(dto);
        List<Label> labelList = page.getRecords();
        List<GetLabelListVo> list = new ArrayList<>();

        if (CollectionUtil.isNotEmpty(labelList)) {
            List<Long> ids = new ArrayList<>();
            List<Long> userIds = new ArrayList<>();

            labelList.forEach(v -> {
                userIds.add(v.getCreator());
                ids.add(v.getId());
            });

            Map<Long, User> userMap = userRepository.getMap(userIds);
            Map<Long, List<GetLabelVo>> listMap = mpRepository.getListByLabelIds(ids);

            for (Label label : labelList) {
                GetLabelListVo vo = new GetLabelListVo();
                BeanUtils.copyProperties(label, vo);
                User operation = userMap.get(label.getCreator());
                if (operation != null) {
                    vo.setCreateName(operation.getName());
                }
                List<GetLabelVo> roleDtoList = listMap.get(label.getId());
                if (roleDtoList != null) {
                    vo.setCaseNumber(roleDtoList.size());
                }
                list.add(vo);
            }
        }


        return new PageResult<>(list, page);

    }

    /**
     * 获取标签下拉列表
     *
     * @param param
     * @return
     */
    @Override
    public List<GetLabelDownListVo> getLabelDownList(GetLabelDownListParam param) {
        Label po = new Label();
        if (param != null) {
            BeanUtils.copyProperties(param, po);
            po.setIsDelete(false);
        }
        List<Label> labelList = labelRepository.getListByEntity(po);

        List<GetLabelDownListVo> list = new ArrayList<>();
        for (Label label : labelList) {
            GetLabelDownListVo vo = new GetLabelDownListVo();
            BeanUtils.copyProperties(label, vo);
            list.add(vo);
        }
        return list;
    }

    /**
     * 清洗这个label是否系统
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateLabel() {
        List<Label> labels = labelRepository.getBaseMapper().selectList(new LambdaQueryWrapper<>());
        for (Label label : labels) {
            label.setIsSystem(false);
            label.setType(0);
        }
        labelRepository.updateBatchById(labels);

    }


}



